<?php
/**
 * 主任务表控制器
 */

namespace app\admin\controller;

use think\Request;
use app\common\model\UserOrder;
use app\common\model\UserSubOrder;
use app\common\model\UserMerchant;

use app\common\validate\UserOrderValidate;

class UserOrderController extends Controller
{
    //列表
    public function index(Request $request, UserOrder $model)
    {
        $param = $request->param();
        $model  = $model->scope('where', $param);
        if (isset($param['export_data']) && $param['export_data'] == 1) {
            $header = ['ID','主订单编号','商家id','商品主图','价格','关键词','发货地址','商品链接','购买开始日期','每单返金币','单数','数量','规格','0 待发布 1进行中 2已结束','创建时间',];
            $body   = [];
            $data   = $model->select();
            foreach ($data as $item) {
                $record       = [];
                $record['id'] = $item->id;
                $record['order_no'] = $item->order_no;
                $record['mid'] = $item->mid;
                $record['image'] = $item->image;
                $record['price'] = $item->price;
                $record['keyword'] = $item->keyword;
                $record['address'] = $item->address;
                $record['url'] = $item->url;
                $record['order_time'] = $item->order_time;
                $record['back_gold'] = $item->back_gold;
                $record['task_num'] = $item->task_num;
                $record['buy_num'] = $item->buy_num;
                $record['attr_name'] = $item->attr_name;
                $record['status'] = $item->status_text;
                $record['create_time'] = $item->create_time;

                $body[]       = $record;
            }
            return $this->exportData($header, $body, 'user_order-' . date('Y-m-d-H-i-s'));
        }
        $data = $model->paginate($this->admin['per_page'], false, ['query'=>$request->get()]);
        //关键词，排序等赋值
        $this->assign($request->get());

        $this->assign([
            'data'  => $data,
            'page'  => $data->render(),
            'total' => $data->total(),
        ]);
        return $this->fetch();
    }

    //添加
    public function add(Request $request, UserOrder $model, UserOrderValidate $validate)
    {
        //查找商家信息
        $bus = UserMerchant::select();
        $this->assign('bus',$bus);

        //生成订单号
        $order_sn = $this->createOrderNm();
        //查询订单里是否存在该订单
        $orderSn = UserOrder::find($order_sn);
        if($orderSn)
        {
            $order_sn = $this->createOrderNm();
        }

        if ($request->isPost()) {

            $param           = $request->param();
            $or = $param['order_no'];
            if(!$or)
            {
                $param['order_no'] = $order_sn;
            }

            $validate_result = $validate->scene('add')->check($param);
            if (!$validate_result) {
                return error($validate->getError());
            }
            //处理商品主图上传
            $attachment_image = new \app\common\model\Attachment;
            $file_image       = $attachment_image->upload('image');
            if ($file_image) {
                $param['image'] = $file_image->url;
            } else {
                return error($attachment_image->getError());
            }

            $param['require_content'] = $request->param(false)['require_content'];

            $result = $model::create($param);

            $url = URL_BACK;
            if(isset($param['_create']) && $param['_create']==1){
                $url = URL_RELOAD;
            }

            //生成子任务
            if($result->id)
            {
                $buy_num = $param['task_num'];
                $key = $param['keyword'];
                for ($x=0; $x<$buy_num; $x++) {

                    //子任务编号
                    $son_sn = $this->createOrderNm();
                    //查询订单里是否存在该订单
                    $sonSn = UserSubOrder::find($son_sn);
                    if($sonSn)
                    {
                        $son_sn = $this->createOrderNm();
                    }

                    $sonData = [
                        'task_id'=>$result->id,
                        'order_no'=>$order_sn,
                        'task_no'=>$son_sn,
                        'keywords'=>$key,
                        'type_id'=>0,
                        'order_time'=>$result->order_time,
                        'create_time'=>time()
                    ];

                    UserSubOrder::create($sonData);
                }
            }

            return $result ? success('添加成功',$url) : error();
        }

        return $this->fetch();
    }

    //修改
    public function edit($id, Request $request, UserOrder $model, UserOrderValidate $validate)
    {
        //查找商家信息
        $bus = UserMerchant::select();
        $this->assign('bus',$bus);

        $data = $model::get($id);
        if ($request->isPost()) {
            $param           = $request->param();
            $validate_result = $validate->scene('edit')->check($param);
            if (!$validate_result) {
                return error($validate->getError());
            }
            //处理商品主图上传
            if (!empty($_FILES['image']['name'])) {
                $attachment_image = new \app\common\model\Attachment;
                $file_image       = $attachment_image->upload('image');
                if ($file_image) {
                    $param['image'] = $file_image->url;
                }
            }

            $param['require_content'] = $request->param(false)['require_content'];

            $result = $data->save($param);
            return $result ? success() : error();
        }

        $this->assign([
            'data' => $data,
        ]);
        return $this->fetch('add');

    }

    //删除
    public function del($id, UserOrder $model)
    {
        if (count($model->noDeletionId) > 0) {
            if (is_array($id)) {
                if (array_intersect($model->noDeletionId, $id)) {
                    return error('ID为' . implode(',', $model->noDeletionId) . '的数据无法删除');
                }
            } else if (in_array($id, $model->noDeletionId)) {
                return error('ID为' . $id . '的数据无法删除');
            }
        }

        if ($model->softDelete) {
            $result = $model->whereIn('id', $id)->useSoftDelete('delete_time', time())->delete();
        } else {
            $result = $model->whereIn('id', $id)->delete();
        }

        return $result ? success('操作成功', URL_RELOAD) : error();
    }

    //订单生成
    public function createOrderNm()
    {
        $year_code = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z');
        $date_code = array('0',
            '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A',
            'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M',
            'N', 'O', 'P', 'Q', 'R', 'T', 'U', 'V', 'W', 'X', 'Y');

        //一共15位订单号,同一秒内重复概率1/10000000,26年一次的循环\
        $order_sn = $year_code[(intval(date('Y')) - 2010) % 26] . //年 1位
            strtoupper(dechex(date('m'))) . //月(16进制) 1位
            $date_code[intval(date('d'))] . //日 1位
            substr(time(), -5) . substr(microtime(), 2, 5) . //秒 5位 // 微秒 5位
            sprintf('%02d', rand(0, 99)); //  随机数 2位

        return $order_sn;
    }


}